package com.natasha.pins.view;

import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.natasha.pins.R;
import com.natasha.pins.bh.pinsmaster.Datasource;
import com.natasha.pins.bh.pinsmaster.PinsMasterBH;
import com.natasha.pins.data.bean.PinsMasterBean;
import com.natasha.pins.util.Constants;
import com.natasha.pins.view.activity.PinsEditActivity;
import com.natasha.pins.view.adapter.AdptrPinBean;

public class MainActivity extends ListActivity {

	private Datasource datasource; 
    private static final int PAGESIZE = 10;
    private TextView textViewDisplaying; 
    
	private AdptrPinBean adapterPinBean;
	private PinsMasterBH pinsMasterBH;
	private View footerView;
	private boolean loading = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		datasource = Datasource.getInstance(this);
		/*
		pinsMasterBH = new PinsMasterBH(this);
		pinsMasterBH.fetchAllPins();
		//AdptrPinBeanStaticVals adapterPinBean = new AdptrPinBeanStaticVals(this);
		//setListAdapter(adapter);
		*/
		footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.pins_list_footer, null, false);
		getListView().addFooterView(footerView, null, false);       
		adapterPinBean = new AdptrPinBean(this, R.layout.pin_bean, datasource.getData(0, PAGESIZE) );
		setListAdapter(adapterPinBean);
		getListView().removeFooterView(footerView);
		
		getListView().setOnScrollListener(new OnScrollListener()
		{			
			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1)
			{
				// nothing here				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
			{
				boolean lastItem = (firstVisibleItem + visibleItemCount == totalItemCount);
				boolean moreRows = getListAdapter().getCount() < datasource.getSize();
				
				if (!loading &&  lastItem && moreRows)
				{
					loading = true;
					getListView().addFooterView(footerView, null, false);
					(new LoadNextPage()).execute("");					
				}				
			}
		});
		
		updateDisplayingTextView();
		
		registerForContextMenu(getListView());
		
	}
	
	private void updateDisplayingTextView(){
		textViewDisplaying = (TextView) findViewById(R.id.displaying);
        String text = getString(R.string.display);
        text = String.format(text, getListAdapter().getCount(), datasource.getSize());
        textViewDisplaying.setText(text);  
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id){
		super.onListItemClick(l, v, position, id);
		PinsMasterBean bean = (PinsMasterBean) getListAdapter().getItem(position);
		Log.d(Constants.LOG_DEBUG, this.getClass().getName() +".onListItemClick item clicked["+bean.getPmid()+"]");
		
		Intent i = new Intent(this, PinsEditActivity.class);
		i.putExtra(PinsMasterBean.NAME_PMID, Long.valueOf(bean.getPmid()));
		startActivityForResult(i, Constants.ACTIVITY_EDIT);
		//i.putExtra("RowId", id);
		//startActivity(i);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent){
		super.onActivityResult(requestCode, resultCode, intent);
		Log.d(Constants.LOG_DEBUG, this.getClass().getName() +".onActivityResult calling refreshData()");
//		pinsMasterBH.fetchAllPins();
//		adapterPinBean.setData(pinsMasterBH.getPinsMasterBeanList());
//		((AdptrPinBean) getListAdapter()).notifyDataSetInvalidated();
		//adapterPinBean.refreshData();
		//adapterPinBean.notifyDataSetChanged();
		//setListAdapter(adapterPinBean);
		//adapterPinBean.fillData();
		
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
		super.onCreateContextMenu(menu, v, menuInfo);
		
		MenuInflater mi = getMenuInflater();
		mi.inflate(R.menu.menu_pin_item, menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater mi = getMenuInflater();
		mi.inflate(R.menu.menu_main, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item){
		
		switch(item.getItemId()){
			case R.id.menu_create_pin:
				createPin();
				return true;
			case R.id.menu_deleteAll:
				deleteAll();
				return true;
			case R.id.menu_share_pin:
				sharePin();
				return true;
				
		}
		
		return super.onMenuItemSelected(featureId, item);
	}

	private void createPin()
	{
		Intent i = new Intent(this, PinsEditActivity.class);
		startActivityForResult(i, Constants.ACTIVITY_CREATE);
	}
	
	private void deleteAll()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setMessage(getString(R.string.del_all_confirm))
				.setCancelable(false)
				.setPositiveButton("Yes", 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								pinsMasterBH.deleteAllPins();
							}
						})
				.setNegativeButton("No", 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						})
				;
		builder.create().show();
	}
	
	private void sharePin()
	{
		Intent i = new Intent(Intent.ACTION_SEND);
		i.setType("text/plain");
		i.putExtra(Intent.EXTRA_TEXT, "Hey everybody!");
		i.putExtra(Intent.EXTRA_SUBJECT, "My subject");
		Intent chooser = Intent.createChooser(i, "Who should handle this?");
		startActivity(chooser);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.context_menu_delete_pin:
			//Delete the pin
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
			PinsMasterBean bean = (PinsMasterBean) getListAdapter().getItem(info.position);
			pinsMasterBH.deletePin(bean.getPmid());
			//adapterPinBean.fillData();
			return true;
		}
		
		return super.onContextItemSelected(item);
	}
	
	private class LoadNextPage extends AsyncTask<String, Void, String>
    {           
        private List<PinsMasterBean> newData = null;
        @Override
        protected String doInBackground(String... arg0)
        {
            //para que de tiempo a ver el footer <img src="http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif?m=1129645325g" alt=";)" class="wp-smiley"> 
            try
            {
                Thread.sleep(1500);
            }
            catch (InterruptedException e)
            {
                Log.e("EndlessListView", e.getMessage());                   
            }
               newData = datasource.getData(getListAdapter().getCount(), PAGESIZE);
               return null;
        }
         
        @Override
        protected void onPostExecute(String result)
        {               
            AdptrPinBean customArrayAdapter = ((AdptrPinBean) getListAdapter());
            for (PinsMasterBean value : newData)
            {
             customArrayAdapter.add(value);
            }
            customArrayAdapter.notifyDataSetChanged();
                 
            getListView().removeFooterView(footerView);
            updateDisplayingTextView();
            loading = false;
        }
         
    }
}
